package com.yue.redisson.controller;

import com.yue.redisson.common.RedissonService;
import com.yue.redisson.domain.User;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;

@Controller
public class TestService {

    private static final Logger log = LoggerFactory.getLogger(TestService.class);
    //获取一个锁对象实例

    @Autowired
    private RedissonService redissonService;
    @Autowired
    private RedissonClient redissonClient;


    @RequestMapping(value = "/test")
    @ResponseBody
    public void test(String recordId) {
        RLock lock = redissonService.getRLock(recordId);
        try {
            boolean bs = lock.tryLock(5, 6, TimeUnit.SECONDS);
            if (bs) {
                // 业务代码
                log.info("进入业务代码: " + recordId);
                RBucket<Object> bucket = redissonClient.getBucket("javaboy");
                bucket.set("www.javaboy.org");
                Object o = bucket.get();
                System.out.println(o);
            } else {
                Thread.sleep(300);
            }
        } catch (Exception e) {
            log.error("", e);
        } finally {
            lock.unlock();
        }
    }

    @RequestMapping(value = "/test2")
    @ResponseBody
    public Object test2() {
        RList<Object> list = redissonClient.getList("user");
        return list;
    }

    @RequestMapping(value = "/test3")
    @ResponseBody
    public boolean test3(String name) {
        User user = new User();
        user.setName(name);
        user.setAge(18);
        user.setPassword("123");
        RList<Object> list = redissonClient.getList("user");
        list.add(user);
        return true;
    }

    @RequestMapping(value = "/test4")
    @ResponseBody
    public boolean test4(String key) {
        redissonClient.getList(key).clear();
        return true;
    }

    public static void main(String[] args) {
        DecimalFormat df=new DecimalFormat("0.000");
        System.out.println( df.format(0.43));
    }
}